<template>
  <view class="page" v-cloak>
	  <fu-custom :isBack="true" :isBottom="true" bgColor="bg-white">
	  	<view slot="content">{{i18n["地址管理"]}}</view>
	  </fu-custom>
    <!-- 地址列表 start -->
    <view class="">
      <block v-for="(item,index) in address_list" :key="index">
        <view class="padding-lr margin-bottom-20 bg-white" >
          <view class="padding-tb-sm" @click="handleClick(item)">
            <view class="flex align-center">
              <view class='cu-tag bg-orange2 radius sm ' v-if='item.label_name'>{{item.label_name}}</view>
              <view >
                {{item.name}}
                <text v-if="item.sex == 1">({{i18n['先生']}})</text>
                <text v-if="item.sex == 2">({{i18n['女士']}})</text>
              </view>
              <view class="margin-left">{{item.mobile | filterMobile}}</view>
            </view>
            <view class="text-666 margin-top-sm">
              {{ item.province }} {{ item.city }} {{ item.district }} {{ item.address }}
            </view>
          </view>
          <view class="flex justify-between align-center solid-top height-100">
            <view class="flex align-center" @click='changeStatus(item)'>
              <text v-if="item.is_default == 1" class="text-xl cuIcon-roundcheckfill active"></text>
              <text v-else class="text-xl cuIcon-round"></text>
              <text class="text-666 margin-left-xs">
                {{item.is_default == 1 ? i18n['默认地址'] : i18n['设为默认']}}
              </text>
            </view>
            <view class="flex text-666">
              <view @click='delAddr(item)' class=" flex align-center">
                <!-- <text class="cuIcon-delete"></text> -->
                <image class="address-icon" :src="imgWechatUrl+'/address/adress-del.png'" mode=""></image>
                <text class="margin-left-xs">{{i18n['删除']}}</text>
              </view>
              <view class="margin-left  flex align-center" @click='edit(item)'>
                <!-- <text class="cuIcon-edit"></text> -->
                <image class="address-icon" :src="imgWechatUrl+'/address/adress-update.png'" mode=""></image>
                <text class="margin-left-xs">{{i18n['编辑']}}</text>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>
    <!-- 地址列表 end -->
    <!-- 空列表展示 start -->
    <fu-empty-ui :pagingListNoListDataText="i18n['您未添加任何地址']" v-if="address_list.length == 0 && isInit"></fu-empty-ui>
    <!-- 空列表展示 end -->
    <!-- 底部占位 start -->
    <view class="bottom-status"></view>
    <!-- 底部占位 end -->
    <!-- 操作按钮 start -->
    <view class="bottom-action">
      <!-- #ifdef MP-WEIXIN -->
      <view class="btn1" @click="importWxAddress">{{i18n['导入微信地址']}}</view>
      <!-- #endif -->
      <view class="btn2" @click="add_Addr">{{i18n['添加地址']}}</view>
    </view>
    <!-- 操作按钮 end -->
    <!-- 断网检测 start -->
    <fu-notwork></fu-notwork>
    <!-- 断网检测 end -->
  </view>
</template>

<script>
  export default {
    data() {
      return {
        checkInx: 0, // 选中地址的下标
				imgWechatUrl:this.imgWechatUrl,
        address_list: [], // 地址列表
        is_change: 0, // 是否开启选择地址模式
        choose_id: 0, // 已选择的默认地址
        edit_id: 0, // 要编辑的地址ID
        backData: null, // 选择低脂模式下的返回值
        isInit: false, // 是否是初始加载,控制数据为空时空布局组件展示与否
      };
    },
    onShow() {
      // 获取地址列表
      this.getAddressList();
    },
    /**
     * @param {object} options 页面入参
     * @param {string} type = 是否需要选择地址 0:不需要 1:需要
     * @param {string} id = 已有默认选中地址 0:没有 id:下单页已选择地址
     */
    onLoad(options) {
      const { type = 0, id = 0 } = options;
      this.is_change = type;
      this.choose_id = id;
      // 提前开启地址授权提示
      uni.getLocation({
        geocode: true,
        success: (adr) => { },
      });
    },
    /**
     * @description 页面出栈
     */
    onUnload() {
      // 如果是选择地址模式
      if (this.is_change == 1) {
        // 通知下单页或其他页面当前选择的地址信息
        uni.$emit("select_address", this.backData);
      }
    },
    // 下拉刷新
    onPullDownRefresh() {
      this.getAddressList();
    },
    methods: {
      /**
       * @func 获取地址列表
       */
      getAddressList() {
        this.$api.post(global.apiUrls.getUserAddressAddressList)
          .then((res) => {
            console.log("地址列表", res);
            if (res.data.code == 1) {
              this.address_list = res.data.data;
              this.isInit = true;
              // 如果是选择地址模式,作如下处理
              if (this.is_change == 1) {
                // 如果有默认选择的地址,还返回默认选择的地址
                let addrObj = this.address_list.find((item) => {
                  return item.address_id == this.choose_id;
                });
                // 如果没有默认选择的地址,或者选择的地址被删了,选择地址列表里的默认地址
                if (!addrObj) {
                  addrObj = this.address_list.find((item) => {
                    this.choose_id = item.is_default == 1 ? item.address_id : "";
                    return item.is_default == 1;
                  });
                }
                // 如果没有默认地址,选择地址列表的第一个地址
                if (!addrObj) {
                  addrObj = this.address_list[0];
                  if (addrObj) {
                    this.choose_id = this.address_list[0].address_id;
                  }
                }
                // 如果没有地址,返回 null
                if (!addrObj) {
                  addrObj = null;
                }
                this.backData = addrObj;
              }
            } else {
              this.$message.info(res.data.msg);
              this.address_list = [];
              this.backData = null;
            }
            this.$nextTick(function () {
              uni.stopPullDownRefresh();
            });
          });
      },
      /**
       * @description 切换默认地址
       * @param {object} item = 地址详细信息
       */
      changeStatus(item) {
        if (item.is_default == 0) {
          console.log(item)


          this.$api.post(global.apiUrls.updateDefaultAddress, { address_id: item.address_id })
            .then(res => {
              this.getAddressList()
            })

        }
      },
      /**
       * @description 地址点击事件
       * @param {object} item = 地址详细信息
       */
      handleClick(item) {
        // 如果是地址选择模式,返回地址对象设为当前选中地址信息,否则不做操作
        if (this.is_change == 1) {
          this.backData = item;
          uni.navigateBack();
        }
      },
      /**
       * @description 去编辑地址
       * @param {object} item = 地址对象
       */
      edit(item) {
        // 记录编辑的地址ID
        this.edit_id = item.address_id;
        this.add_Addr(item);
      },
      /**
       * @description 删除地址
       * @param {object} item = 地址对象
       * */
      delAddr(item) {
        console.log(item)
        this.$util.showModal({
          title: this.i18n['提示'],
          content: this.i18n['确定删除该地址']+'?',
          confirmColor: this.$store.state.themeColor,
          success: (res) => {
            if (res.confirm) {
              this.$api.post(global.apiUrls.postUserAddressDelAddress, { address_ids: item.address_id })
                .then(res => {
                  console.log(res);
                  if (res.data.code == 1) {
                    this.getAddressList()
                  } else {
                    this.$message.info(res.msg);
                  }
                });
            }
          }

        })
      },
      /**
       * @description 添加地址
       * @param {object} item = 地址对象
       * */
      add_Addr(item) {
        // 有参数是编辑地址,无参数是新增地址
        uni.navigateTo({
          url: "/pages/address/address-add/index?id=" + ((item && item.address_id) || ""),
        });
      },
      // #ifdef MP-WEIXIN
      /**
       * @description 导入微信地址,只在微信小程序有效
       * */
      importWxAddress() {
        console.log('开始导入微信地址')
        uni.chooseAddress({
          success: res => {
            console.log('微信地址==>', res)
            let data = {
              name: res.userName,
              mobile: res.telNumber,
              is_default: '0',
              address: res.detailInfo,
              province: res.provinceName || res.cityName,
              city: res.cityName,
              district: res.countyName,
            };
            this.addAddress(data);
          },
          fail(err) { }
        });
      },
      addAddress(data) {
        if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(data.mobile)) {
					let text = !data.mobile ? this.i18n['请输入手机号'] : this.i18n['手机号格式不正确'];
					this.$message.info(text);
					return false;
				}
        this.$api.post(global.apiUrls.postUserAddressAddAddress, data)
          .then(res => {
            console.log('导入成功', res);
            if (res.statusCode == 200 && res.data.code == 1) {
              this.$message.info(this.i18n['导入成功'])
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            console.log("err: ", err);
          })
      }
      // #endif
    },
  };
</script>

<style lang="scss" scoped>
  .bottom-status {
    height: 156rpx;
    height: calc(156rpx + constant(safe-area-inset-bottom));
    height: calc(156rpx + env(safe-area-inset-bottom));
  }

  .bottom-action {
    position: fixed;
    right: 32rpx;
    left: 32rpx;
    bottom: 56rpx;
    bottom: calc(56rpx + constant(safe-area-inset-bottom));
    bottom: calc(56rpx + env(safe-area-inset-bottom));
    display: flex;

    view {
      height: 88rpx;
      flex: 1;
      line-height: 88rpx;
      text-align: center;
      border-radius: 88rpx;
      color: #FFFFFF;
    }

    .btn1 {
      margin-right: 32rpx;
      background: linear-gradient(126deg, #39b54a 0%, #8dc63f 100%);
    }

    .btn2 {
      background: $bgtheme;
    }
  }

  .active {
    color: $theme;
  }
  .bg-orange2{
    background: #FF9D00;
    color: #fff;
    margin-right:14rpx;
  }
  .address-icon{
	  width: 30rpx;
	  height: 30rpx;
  }
  .margin-bottom-20{
    margin-bottom: 20rpx;
  }
</style>
